/**
 * 🎮 游戏化功能 UI
 * 包含成就系统和等级体系的前端逻辑
 */

// ========================================
// ⭐ 等级系统
// ========================================

// 加载用户等级信息
async function loadUserLevel() {
    try {
        // 先检查必要的DOM元素是否存在
        if (!document.getElementById('userLevelBadge')) {
            return; // 页面上没有游戏化UI元素，直接返回
        }
        
        // 直接调用已包装的API（内部已使用safeGameRequest）
        const result = await api.gamification.getLevel();
        if (!result || !result.data) {
            console.log('游戏化功能未启用，跳过等级加载');
            return;
        }
        const data = result.data;
        
        // 更新顶部等级徽章
        document.getElementById('userLevelBadge').style.display = 'flex';
        document.getElementById('levelIcon').textContent = data.level_icon;
        document.getElementById('levelName').textContent = data.level_name;
        document.getElementById('levelNumber').textContent = data.level;
        
        // 更新游戏统计
        document.getElementById('gameStats').style.display = 'flex';
        document.getElementById('expValue').textContent = data.exp;
        document.getElementById('pointsValue').textContent = data.total_points;
        document.getElementById('streakValue').textContent = data.streak_days;
        
        // 更新等级卡片
        document.getElementById('levelDisplayIcon').textContent = data.level_icon;
        document.getElementById('levelDisplayName').textContent = data.level_name;
        document.getElementById('levelDisplay').textContent = data.level;
        document.getElementById('currentExp').textContent = data.exp;
        document.getElementById('nextLevelExp').textContent = data.next_level_exp;
        document.getElementById('expProgress').style.width = data.progress + '%';
        document.getElementById('totalRecordsDisplay').textContent = data.total_records;
        document.getElementById('streakDisplay').textContent = data.streak_days;
        document.getElementById('totalPointsDisplay').textContent = data.total_points;
        
    } catch (error) {
        // 静默处理错误，不影响主功能
        // 游戏化功能是可选的，不需要显示错误
        hideGameUI();
    }
}

// 隐藏游戏化UI元素
function hideGameUI() {
    const elementsToHide = ['userLevelBadge', 'gameStats'];
    elementsToHide.forEach(id => {
        const el = document.getElementById(id);
        if (el) el.style.display = 'none';
    });
}

// 升级动画
function showLevelUpAnimation(levelInfo) {
    const overlay = document.createElement('div');
    overlay.className = 'level-up-overlay';
    overlay.innerHTML = `
        <div class="level-up-modal">
            <div class="level-up-icon">🎉</div>
            <div class="level-up-title">恭喜升级！</div>
            <div class="level-up-level">
                <span style="font-size: 48px;">${levelInfo.level_icon}</span>
                <div style="font-size: 24px; margin-top: 10px;">${levelInfo.level_name}</div>
                <div style="font-size: 16px; color: #666;">等级 ${levelInfo.new_level}</div>
            </div>
            <button onclick="this.parentElement.parentElement.remove()" class="btn btn-primary" style="margin-top: 20px;">太棒了！</button>
        </div>
    `;
    
    const style = document.createElement('style');
    style.textContent = `
        .level-up-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 10000;
            animation: fadeIn 0.3s;
        }
        .level-up-modal {
            background: white;
            padding: 40px;
            border-radius: 16px;
            text-align: center;
            max-width: 400px;
            animation: scaleIn 0.5s;
        }
        .level-up-icon {
            font-size: 64px;
            animation: bounce 0.8s infinite;
        }
        .level-up-title {
            font-size: 28px;
            font-weight: bold;
            margin: 20px 0;
            background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        @keyframes scaleIn {
            from { transform: scale(0.5); }
            to { transform: scale(1); }
        }
        @keyframes bounce {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-20px); }
        }
    `;
    
    document.head.appendChild(style);
    document.body.appendChild(overlay);
    
    // 播放音效（可选）
    playSound('levelup');
}

// ========================================
// 🏆 成就系统
// ========================================

// 加载成就列表
async function loadAchievements() {
    try {
        // 先检查DOM元素
        if (!document.getElementById('achievementsList')) {
            return;
        }
        
        // 直接调用已包装的API（内部已使用safeGameRequest）
        const result = await api.gamification.getAchievements();
        if (!result || !result.data) {
            console.log('游戏化功能未启用，跳过成就加载');
            return;
        }
        const achievements = result.data;
        
        // 只显示已获得的成就（最多5个）
        const achieved = achievements.filter(a => a.achieved).slice(0, 5);
        
        const container = document.getElementById('achievementsDisplay');
        
        if (achieved.length === 0) {
            container.innerHTML = '<div style="color: #999; text-align: center; padding: 40px;">还没有解锁任何成就<br>开始记账解锁第一个成就吧！</div>';
            return;
        }
        
        container.innerHTML = achieved.map(ach => `
            <div style="padding: 10px; margin-bottom: 8px; background: linear-gradient(135deg, #667eea22 0%, #764ba222 100%); border-radius: 8px; border-left: 4px solid #667eea;">
                <div style="display: flex; align-items: center;">
                    <span style="font-size: 24px; margin-right: 10px;">${ach.achievement_icon}</span>
                    <div style="flex: 1;">
                        <div style="font-weight: bold;">${ach.achievement_name}</div>
                        <div style="font-size: 12px; color: #666;">${ach.achievement_desc}</div>
                    </div>
                    <div style="text-align: right;">
                        <div style="font-size: 12px; color: #fbbc04;">+${ach.points}分</div>
                        <div style="font-size: 10px; color: #999;">${new Date(ach.achieved_at).toLocaleDateString()}</div>
                    </div>
                </div>
            </div>
        `).join('');
        
    } catch (error) {
        console.error('加载成就失败:', error);
    }
}

// 显示全部成就
async function showAllAchievements() {
    try {
        const result = await api.gamification.getAchievements();
        const achievements = result.data;
        
        const modal = document.createElement('div');
        modal.className = 'modal active';
        modal.innerHTML = `
            <div class="modal-content" style="max-width: 600px;">
                <h3 class="modal-title">🏆 全部成就</h3>
                <div style="max-height: 500px; overflow-y: auto;">
                    ${achievements.map(ach => `
                        <div style="padding: 12px; margin-bottom: 10px; background: ${ach.achieved ? 'linear-gradient(135deg, #667eea22 0%, #764ba222 100%)' : '#f5f5f5'}; border-radius: 8px; ${ach.achieved ? 'border-left: 4px solid #667eea' : ''}; opacity: ${ach.achieved ? 1 : 0.5};">
                            <div style="display: flex; align-items: center;">
                                <span style="font-size: 32px; margin-right: 15px;">${ach.achievement_icon}</span>
                                <div style="flex: 1;">
                                    <div style="font-weight: bold; ${!ach.achieved ? 'color: #999' : ''}">${ach.achievement_name} ${ach.achieved ? '✓' : ''}</div>
                                    <div style="font-size: 12px; color: #666;">${ach.achievement_desc}</div>
                                    ${!ach.achieved ? `<div style="font-size: 11px; color: #999; margin-top: 4px;">要求：${ach.requirement_value}次</div>` : ''}
                                </div>
                                <div style="text-align: right;">
                                    <div style="font-size: 14px; color: #fbbc04;">+${ach.points}分</div>
                                    ${ach.achieved ? `<div style="font-size: 10px; color: #999;">${new Date(ach.achieved_at).toLocaleDateString()}</div>` : ''}
                                </div>
                            </div>
                        </div>
                    `).join('')}
                </div>
                <div class="modal-actions">
                    <button class="btn btn-secondary" onclick="this.closest('.modal').remove()">关闭</button>
                </div>
            </div>
        `;
        
        document.body.appendChild(modal);
    } catch (error) {
        console.error('显示全部成就失败:', error);
        showToast('加载失败：' + error.message, 'error');
    }
}

// 检查并显示新成就
async function checkAndShowNewAchievements() {
    try {
        const result = await api.gamification.checkAchievements();
        const newAchievements = result.data.newAchievements;
        
        if (newAchievements && newAchievements.length > 0) {
            // 显示成就解锁动画
            for (const ach of newAchievements) {
                showAchievementUnlocked(ach);
                await new Promise(resolve => setTimeout(resolve, 2000));
            }
            
            // 刷新成就列表
            await loadAchievements();
            await loadUserLevel();
        }
    } catch (error) {
        console.error('检查成就失败:', error);
    }
}

// 成就解锁动画
function showAchievementUnlocked(achievement) {
    const notification = document.createElement('div');
    notification.className = 'achievement-notification';
    notification.innerHTML = `
        <div class="achievement-content">
            <div class="achievement-icon">${achievement.icon}</div>
            <div class="achievement-info">
                <div class="achievement-title">🎉 成就解锁！</div>
                <div class="achievement-name">${achievement.name}</div>
                <div class="achievement-points">+${achievement.points} 积分</div>
            </div>
        </div>
    `;
    
    const style = document.createElement('style');
    style.textContent = `
        .achievement-notification {
            position: fixed;
            top: 20px;
            right: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3);
            z-index: 10000;
            animation: slideInRight 0.5s, slideOutRight 0.5s 1.5s;
        }
        .achievement-content {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .achievement-icon {
            font-size: 48px;
            animation: bounce 0.8s infinite;
        }
        .achievement-title {
            font-size: 12px;
            opacity: 0.9;
        }
        .achievement-name {
            font-size: 18px;
            font-weight: bold;
            margin: 5px 0;
        }
        .achievement-points {
            font-size: 14px;
            opacity: 0.9;
        }
        @keyframes slideInRight {
            from { transform: translateX(400px); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
        @keyframes slideOutRight {
            from { transform: translateX(0); opacity: 1; }
            to { transform: translateX(400px); opacity: 0; }
        }
    `;
    
    document.head.appendChild(style);
    document.body.appendChild(notification);
    
    setTimeout(() => notification.remove(), 2000);
    
    // 播放音效（可选）
    playSound('achievement');
}

// ========================================
// 🏅 排行榜
// ========================================

// 加载游戏排行榜
async function loadGameLeaderboard() {
    try {
        const container = document.getElementById('gameLeaderboard');
        
        // 先检查DOM元素是否存在
        if (!container) {
            return; // 页面上没有游戏化排行榜元素，直接返回
        }
        
        // 直接调用已包装的API（内部已使用safeGameRequest）
        const result = await api.gamification.getGameLeaderboard();
        if (!result || !result.data) {
            console.log('游戏化功能未启用，跳过排行榜加载');
            return;
        }
        const leaderboard = result.data;
        
        if (leaderboard.length === 0) {
            container.innerHTML = '<div style="color: #999; text-align: center; padding: 40px;">暂无数据</div>';
            return;
        }
        
        container.innerHTML = leaderboard.map((user, index) => {
            const medals = ['🥇', '🥈', '🥉'];
            const medal = medals[index] || `${index + 1}.`;
            
            return `
                <div style="padding: 12px; margin-bottom: 8px; background: ${index < 3 ? '#fffbec' : '#f5f5f5'}; border-radius: 8px; display: flex; justify-content: space-between; align-items: center;">
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <span style="font-size: 20px; width: 30px;">${medal}</span>
                        <div>
                            <div style="font-weight: bold;">${user.nickname || user.username}</div>
                            <div style="font-size: 12px; color: #666;">
                                ${user.level_icon} ${user.level_name} Lv.${user.level}
                            </div>
                        </div>
                    </div>
                    <div style="text-align: right;">
                        <div style="font-weight: bold; color: #667eea;">${user.total_points}分</div>
                        <div style="font-size: 11px; color: #666;">${user.total_records}条记录</div>
                    </div>
                </div>
            `;
        }).join('');
        
    } catch (error) {
        // 静默处理错误，游戏化功能是可选的
    }
}

// ========================================
// 🎵 音效（可选）
// ========================================

function playSound(type) {
    // 简单的音效提示，可以替换为实际音效文件
    try {
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        if (type === 'achievement') {
            oscillator.frequency.value = 523.25; // C5
            gainNode.gain.value = 0.3;
            oscillator.start();
            oscillator.stop(audioContext.currentTime + 0.2);
        } else if (type === 'levelup') {
            oscillator.frequency.value = 659.25; // E5
            gainNode.gain.value = 0.3;
            oscillator.start();
            oscillator.stop(audioContext.currentTime + 0.3);
        }
    } catch (error) {
        // 音效播放失败不影响功能
    }
}

// ========================================
// 初始化
// ========================================

// 在页面加载时初始化游戏化功能
window.addEventListener('DOMContentLoaded', () => {
    // 先检查页面上是否有游戏化UI元素
    // 如果没有，就完全不加载游戏化功能，避免不必要的API调用
    const hasGameUI = document.getElementById('userLevelBadge') || 
                      document.getElementById('gameLeaderboard') ||
                      document.getElementById('achievementsList');
    
    if (!hasGameUI) {
        console.log('💡 游戏化功能未启用。如需启用，请运行：添加游戏化功能.bat');
        return; // 没有游戏化UI，完全不调用任何游戏化函数
    }
    
    // 延迟加载，确保用户已登录
    setTimeout(() => {
        loadUserLevel();
        loadAchievements();
        loadGameLeaderboard();
    }, 1000);
});

console.log('🎮 游戏化功能UI已加载'); 